// https://www.lintcode.com/problem/first-position-of-target/

public class Solution {
    /**
     * @param nums: The integer array.
     * @param target: Target to find.
     * @return: The first position of target. Position starts from 0.
     */
    public int binarySearch(int[] nums, int target) {
        // write your code here
        int i = 0, j = nums.length - 1;
        while (i <= j) {
            int mid = (i + j) / 2;
            if (nums[mid] < target) {
                i = mid + 1;
            }
            else if (nums[mid] > target) {
                j = mid - 1;
            }
            else {
                while (mid > 1) { // 这里可继续二分
                    if (nums[mid - 1] != nums[mid]) {
                        return mid;
                    }
                    --mid;
                }
                return mid;
            }
        }
        return -1;
    }
}